<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务详情</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/inter-ui@3.19.3/inter.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                    colors: {
                        primary: {
                            50: '#eef2ff',
                            100: '#e0e7ff',
                            200: '#c7d2fe',
                            300: '#a5b4fc',
                            400: '#818cf8',
                            500: '#6366f1',
                            600: '#4f46e5',
                            700: '#4338ca',
                            800: '#3730a3',
                            900: '#312e81',
                        }
                    }
                }
            }
        }
    </script>
    <style>
        /* 需求文件夹动画效果 */
        .req-files-container {
            transition: max-height 0.3s ease-in-out;
            overflow: hidden;
            max-height: 0;
        }
        
        .rotate-180 {
            transform: rotate(180deg);
        }
        
        /* 文件图标样式 */
        .fa-file-word {
            color: #4285f4;
        }
        
        .fa-file-excel {
            color: #0f9d58;
        }
        
        .fa-file-pdf {
            color: #ea4335;
        }
        
        /* 提高视觉层次感 */
        .req-group-header:hover {
            background-color: #f3f4f6;
        }
        
        .req-group-header {
            transition: background-color 0.2s;
        }
        
        /* 动画效果 */
        .fa-chevron-down {
            transition: transform 0.3s ease;
        }
    </style>
</head>
<body class="bg-gray-50 font-sans min-h-screen flex flex-col">
    <!-- 加载中遮罩 -->
    <div id="loadingOverlay"
         class="fixed inset-0 bg-white bg-opacity-80 z-50 flex items-center justify-center hidden">
        <div class="text-center">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-600"></div>
            <p class="mt-2 text-primary-800 font-medium" id="loadingText">正在处理，请稍候...</p>
        </div>
    </div>

    <!-- 顶部导航 -->
    <nav class="bg-white shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center">
                        <svg class="h-8 w-8 text-primary-600" xmlns="http://www.w3.org/2000/svg" fill="none"
                             viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                  d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                        </svg>
                        <span class="ml-2 text-xl font-semibold text-gray-900">文档智能生成平台</span>
                    </div>
                </div>
                <div class="flex items-center">
                    <a href="/docs"
                       class="ml-4 px-3 py-2 rounded-md text-sm font-medium text-gray-700 hover:text-gray-900 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-primary-500">
                        <i class="fas fa-home mr-1"></i> 首页
                    </a>
                    <a href="/tasks/list"
                       class="ml-4 px-3 py-2 rounded-md text-sm font-medium text-primary-700 hover:text-primary-800 hover:bg-primary-100 focus:outline-none focus:ring-2 focus:ring-primary-500">
                        <i class="fas fa-tasks mr-1"></i> 任务管理
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主容器 -->
    <main class="flex-grow max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div class="bg-white shadow-sm sm:rounded-lg overflow-hidden">
            <div class="px-4 py-5 sm:p-6">
                <div class="flex items-center mb-4">
                    <div class="flex-shrink-0 h-10 w-10 rounded-full bg-primary-100 flex items-center justify-center">
                        <i class="fas fa-clipboard-list text-primary-600"></i>
                    </div>
                    <h3 class="ml-3 text-lg font-medium text-gray-900">任务详情</h3>
                </div>

                <!-- 任务状态条 -->
                <div class="mb-8 px-4 py-4 bg-gray-50 rounded-lg">
                    <div class="flex flex-wrap items-center justify-between">
                        <div class="flex items-center mb-2 sm:mb-0">
                            <div class="mr-4">
                                <span class="block text-sm font-medium text-gray-500">任务状态</span>
                                <span id="taskStatus" class="mt-1 text-sm"></span>
                            </div>
                            <div class="mr-4">
                                <span class="block text-sm font-medium text-gray-500">任务ID</span>
                                <span id="taskId" class="mt-1 text-sm text-gray-900" th:text="${task.taskId}"></span>
                            </div>
                        </div>
                        <div class="flex items-center">
                            <div class="mr-4">
                                <span class="block text-sm font-medium text-gray-500">创建时间</span>
                                <span id="createTime" class="mt-1 text-sm text-gray-900" th:text="${#temporals.format(task.createTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
                            </div>
                            <div>
                                <span class="block text-sm font-medium text-gray-500">完成时间</span>
                                <span id="completeTime" class="mt-1 text-sm text-gray-900" th:text="${task.completeTime != null ? #temporals.format(task.completeTime, 'yyyy-MM-dd HH:mm:ss') : '-'}"></span>
                            </div>
                        </div>
                    </div>
                    <div class="mt-3" th:if="${task.status == 'PROCESSING'}">
                        <div class="w-full bg-gray-200 rounded-full h-2.5">
                            <div class="bg-blue-500 h-2.5 rounded-full" th:style="'width: ' + ${task.progress} + '%'"></div>
                        </div>
                        <div class="mt-1 text-xs text-gray-500 text-right" th:text="${task.progress} + '%'"></div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="mb-8" th:if="${task.status == 'COMPLETED'}">
                    <div class="flex flex-wrap space-x-4">
                        <button type="button" id="downloadBtn"
                                th:attr="data-path=${task.outputDir}"
                                class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                            <i class="fas fa-download mr-2"></i> 下载全部文件
                        </button>
                    </div>
                </div>

                <!-- 错误信息 -->
                <div class="mb-8" th:if="${task.status == 'FAILED' && task.errorMessage != null}">
                    <div class="bg-red-50 border-l-4 border-red-400 p-4">
                        <div class="flex">
                            <div class="flex-shrink-0">
                                <i class="fas fa-exclamation-circle text-red-400"></i>
                            </div>
                            <div class="ml-3">
                                <h3 class="text-sm font-medium text-red-800">任务执行失败</h3>
                                <div class="mt-2 text-sm text-red-700">
                                    <p th:text="${task.errorMessage}"></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 文件列表 -->
                <div class="mt-8" th:if="${not #lists.isEmpty(files)}">
                    <h4 class="text-base font-medium text-gray-900 mb-4">生成的文件</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col"
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        需求编号
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        需求名称
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        文件名
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        大小
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        类型
                                    </th>
                                    <th scope="col"
                                        class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        操作
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <tr th:each="file : ${files}">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900" th:text="${file.reqNo ?: '-'}"></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900" th:text="${file.reqName ?: '-'}"></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <i th:class="${'fas mr-2 ' + (file.fileType == 'XLSX' ? 'fa-file-excel text-green-500' : file.fileType == 'DOCX' ? 'fa-file-word text-blue-500' : file.fileType == 'PDF' ? 'fa-file-pdf text-red-500' : 'fa-file text-gray-500')}"></i>
                                            <div class="text-sm text-gray-900" th:text="${file.fileName ?: (file.filePath != null ? #strings.substringAfterLast(#strings.replace(file.filePath, '\\', '/'), '/') : '-')}"></div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900" th:text="${#numbers.formatDecimal(file.fileSize / 1024, 0, 2)} + 'KB'"></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900 uppercase" th:text="${file.fileType}"></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                        <button type="button" class="text-primary-600 hover:text-primary-900"
                                                th:attr="data-path=${file.filePath}"
                                                onclick="openFile(this.getAttribute('data-path'))">
                                            <i class="fas fa-download mr-1"></i> 下载
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 返回按钮 -->
                <div class="mt-8 flex justify-end">
                    <a href="/tasks/list"
                       class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                        <i class="fas fa-arrow-left mr-2"></i> 返回任务列表
                    </a>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 mt-auto">
        <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
            <p class="text-center text-sm text-gray-500">© 2025 文档智能生成平台 | 版本 2.0</p>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 更新任务状态标签
            const status = "[[${task.status}]]";
            const statusElement = document.getElementById('taskStatus');
            
            let badgeClass, icon, text;
            switch (status) {
                case 'PENDING':
                    badgeClass = 'bg-yellow-100 text-yellow-800';
                    icon = 'fa-clock';
                    text = '等待中';
                    break;
                case 'PROCESSING':
                    badgeClass = 'bg-blue-100 text-blue-800';
                    icon = 'fa-spinner fa-spin';
                    text = '处理中';
                    break;
                case 'COMPLETED':
                    badgeClass = 'bg-green-100 text-green-800';
                    icon = 'fa-check';
                    text = '已完成';
                    break;
                case 'FAILED':
                    badgeClass = 'bg-red-100 text-red-800';
                    icon = 'fa-exclamation-triangle';
                    text = '失败';
                    break;
                default:
                    badgeClass = 'bg-gray-100 text-gray-800';
                    icon = 'fa-question';
                    text = '未知';
            }
            
            statusElement.innerHTML = `<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${badgeClass}">
                <i class="fas ${icon} mr-1"></i> ${text}
            </span>`;
            
            // 下载按钮事件
            const downloadBtn = document.getElementById('downloadBtn');
            if (downloadBtn) {
                downloadBtn.addEventListener('click', function() {
                    const path = this.getAttribute('data-path');
                    if (path) {
                        window.location.href = '/docs/download-zip?path=' + encodeURIComponent(path);
                    }
                });
            }
            
            // 如果任务正在处理中，自动刷新页面
            if (status === 'PROCESSING') {
                setTimeout(() => {
                    window.location.reload();
                }, 5000);
            }
            
            // 在前端实现文件分组功能
            organizeFilesByRequirement();
        });
        
        // 打开文件
        function openFile(path) {
            try {
                fetch('/docs/open-file?path=' + encodeURIComponent(path))
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.data && data.data.downloadUrl) {
                            // 使用下载链接下载文件
                            window.location.href = data.data.downloadUrl;
                        } else {
                            alert('无法获取文件下载链接: ' + (data.message || '未知错误'));
                        }
                    })
                    .catch(() => {
                        alert('无法打开文件，请确保文件存在并且系统支持此操作');
                    });
            } catch (e) {
                alert('尝试打开文件时出错: ' + e.message);
            }
        }
        
        // 前端将文件按需求分组显示
        function organizeFilesByRequirement() {
            // 获取原始文件表格
            const fileTable = document.querySelector('.overflow-x-auto');
            if (!fileTable) return;
            
            // 获取所有文件行
            const fileRows = Array.from(fileTable.querySelectorAll('tbody tr'));
            if (fileRows.length === 0) return;
            
            // 创建分组容器
            const filesByReqContainer = document.createElement('div');
            filesByReqContainer.id = 'filesByReq';
            filesByReqContainer.className = 'space-y-4 mt-4';
            
            // 按需求编号分组
            const filesByReq = {};
            fileRows.forEach(row => {
                const reqNo = row.querySelector('td:first-child').textContent.trim();
                const reqName = row.querySelector('td:nth-child(2)').textContent.trim();
                
                if (!filesByReq[reqNo]) {
                    filesByReq[reqNo] = {
                        reqName: reqName !== '-' ? reqName : '',
                        files: []
                    };
                }
                
                filesByReq[reqNo].files.push(row);
            });
            
            // 创建分组DOM结构
            Object.keys(filesByReq).forEach(reqNo => {
                const group = filesByReq[reqNo];
                
                // 创建需求组容器
                const reqGroup = document.createElement('div');
                reqGroup.className = 'border rounded-lg overflow-hidden';
                
                // 创建需求组标题
                const reqHeader = document.createElement('div');
                reqHeader.className = 'req-group-header bg-gray-50 px-4 py-3 cursor-pointer hover:bg-gray-100 transition-colors flex justify-between items-center';
                reqHeader.dataset.reqNo = reqNo;
                
                reqHeader.innerHTML = `
                    <div class="flex items-center">
                        <i class="fas fa-folder text-yellow-500 mr-2"></i>
                        <div>
                            <span class="font-medium text-gray-900">${reqNo}</span>
                            ${group.reqName ? `<span class="ml-2 text-gray-600">${group.reqName}</span>` : ''}
                        </div>
                    </div>
                    <div class="flex items-center">
                        <span class="text-sm text-gray-500 mr-3">${group.files.length} 个文件</span>
                        <i class="fas fa-chevron-down text-gray-400 transform transition-transform duration-200"></i>
                    </div>
                `;
                
                // 创建文件列表容器
                const filesContainer = document.createElement('div');
                filesContainer.className = 'req-files-container bg-white';
                filesContainer.style.display = 'none';
                filesContainer.style.maxHeight = '0';
                filesContainer.style.transition = 'max-height 0.3s ease-in-out';
                filesContainer.style.overflow = 'hidden';
                
                // 创建文件表格
                const table = document.createElement('table');
                table.className = 'min-w-full divide-y divide-gray-200';
                
                // 创建表头
                const thead = document.createElement('thead');
                thead.className = 'bg-gray-50';
                thead.innerHTML = `
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            文件名
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            大小
                        </th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            类型
                        </th>
                        <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                    </tr>
                `;
                
                // 创建表体
                const tbody = document.createElement('tbody');
                tbody.className = 'bg-white divide-y divide-gray-200';
                
                // 添加文件行
                group.files.forEach(row => {
                    const newRow = document.createElement('tr');
                    
                    // 从第3列开始复制内容（跳过reqNo和reqName列）
                    const cells = row.querySelectorAll('td');
                    for (let i = 2; i < cells.length; i++) {
                        const newCell = cells[i].cloneNode(true);
                        newRow.appendChild(newCell);
                    }
                    
                    tbody.appendChild(newRow);
                });
                
                // 组合表格
                table.appendChild(thead);
                table.appendChild(tbody);
                
                // 添加表格到文件容器
                const tableContainer = document.createElement('div');
                tableContainer.className = 'overflow-x-auto';
                tableContainer.appendChild(table);
                filesContainer.appendChild(tableContainer);
                
                // 组合需求组
                reqGroup.appendChild(reqHeader);
                reqGroup.appendChild(filesContainer);
                
                // 添加需求组到分组容器
                filesByReqContainer.appendChild(reqGroup);
                
                // 添加展开/折叠事件
                reqHeader.addEventListener('click', function() {
                    const icon = this.querySelector('.fa-chevron-down');
                    const filesContainer = this.nextElementSibling;
                    
                    if (filesContainer.style.display === 'none') {
                        filesContainer.style.display = 'block';
                        icon.classList.add('rotate-180');
                        
                        // 添加动画效果
                        setTimeout(() => {
                            filesContainer.style.maxHeight = filesContainer.scrollHeight + 'px';
                        }, 10);
                    } else {
                        icon.classList.remove('rotate-180');
                        filesContainer.style.maxHeight = '0';
                        
                        // 动画完成后隐藏
                        setTimeout(() => {
                            filesContainer.style.display = 'none';
                        }, 300);
                    }
                });
            });
            
            // 替换原始表格
            fileTable.parentNode.replaceWith(filesByReqContainer);
            
            // 默认展开第一个需求组
            const firstReqHeader = document.querySelector('.req-group-header');
            if (firstReqHeader) {
                firstReqHeader.click();
            }
        }
    </script>
</body>
</html> 